
// src/storage/mod.rs
use crate::todo::Todo;
use std::fs::{File, OpenOptions};
use std::io::{BufReader, BufWriter, Error, ErrorKind};
use std::path::PathBuf;
use std::io::{Write, BufRead};

const DATA_FILE: &str = "todos.data";

pub fn save_todos(todos: &[Todo]) -> Result<(), Error> {
    let path = PathBuf::from(DATA_FILE);
    let file = OpenOptions::new()
        .write(true)
        .create(true)
        .truncate(true)
        .open(&path)?;

    let mut writer = BufWriter::new(file);

    for todo in todos {
        let line = format!("{}\t{}\n", todo.description, todo.completed);
        writer.write_all(line.as_bytes())?;
    }

    Ok(())
}

pub fn load_todos() -> Result<Vec<Todo>, Error> {
    let path = PathBuf::from(DATA_FILE);
    let file = File::open(&path).map_err(|_| Error::new(ErrorKind::NotFound, "Data file not found"))?;
    let reader = BufReader::new(file);

    let mut todos = Vec::new();

    for line in reader.lines() {
        let line = line?;
        let parts: Vec<&str> = line.split('\t').collect();

        if parts.len() == 2 {
            let description = parts[0].to_owned();
            let completed = parts[1].parse().unwrap_or(false);
            todos.push(Todo {
                description,
                completed,
            });
        }
    }

    Ok(todos)
}

